<?php

namespace App\Http\Services;

use App\Models\Wework;
use App\Repositories\Api\MemberRepository;
use EasyWeChat\Factory;

use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Log;

/**
 * 企微
 * @package App\Http\Services
 */
class WeworkService
{
    public $easyWeChat;
    private $config;
    public $sendData;

    public function __construct()
    {
        $this->config = [
            'corp_id' => "wwaee2d2254317a1f5",
            'secret' => "8cCBcbE_InBju7ULA62WVhBZQS7letYRCCU06o7cJJY",
            'response_type' => 'array',
            'log' => [
                "file" => "/opt/logs/easywechat-wework.log"
            ],
            'http' => [
                'max_retries' => 1,
                'retry_delay' => 500,
                'timeout' => 5.0,
            ],
        ];

        $this->easyWeChat = Factory::work($this->config);
    }

    public function getFollowUsers()
    {
        try {
//            $detail = $this->easyWeChat->external_contact->get("wmsD7FDQAA0v50n1MJ0oQPS2_2Q2lmJA");
//            $users = $this->easyWeChat->external_contact->getFollowUsers();
            $userId = "ChenYaoLin";
            $users = $this->easyWeChat->external_contact->list($userId);

            foreach ($users['external_userid'] as $k => $v) {
                $detail = $this->getExternalUserDetail($v);
                dd($detail);
            }
            dd($users);
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }

    /**
     * 更新备注
     * @param null $uid 联谊id
     * @param null $remark
     * @return bool
     */
    public function updateRemark($uid = null, $remark = null)
    {
        if (!trim($uid))
            return false;

        $condition = [];
        if (is_numeric($uid)) {
            $condition['uid'] = intval($uid);
        } else {
            $condition['unionid'] = $uid;
        }
        $weworks = Wework::query()->where($condition)->get(['id', 'external_userid', 'wework_userid', 'remark'])->toArray();
        if (empty($weworks) || count($weworks) == 0)
            return false;

        //        获取remark
        empty($remark) && $remark = (new MemberRepository())->getWeworkRemark($uid);
        try {
            foreach ($weworks as $k => $wework) {
                if (!empty($wework['remark']) && $remark == $wework['remark']) {
                    continue;
                }

                $data = [
                    'userid' => $wework['wework_userid'],
                    'external_userid' => $wework['external_userid'],
                    'remark' => $remark,
                ];
                $res = $this->easyWeChat->external_contact->remark($data);

                if ($res['errcode'] == 0) {
                    Wework::query()->where(['id' => $wework['id']])->update([
                        'remark' => $remark,
                        'is_complete' => (count(explode("-", $remark)) == 6 ? 1 : 0)
                    ]);

                    continue;
                } else {
//                    Log::channel("log")->error("wework update remark: " . json_encode($res));
                }
            }

            return true;
        } catch (Exception $e) {
//            Log::channel("log")->error("wework remark exception: " . $e->getMessage());
            return false;
        }
    }

    /**
     * 获取外部联系人 - 所有
     * @param null $userId 客户ID
     * @throws Exception
     */
    public function getExternalList($userId = null)
    {
        if (empty($userId))
            throw  new Exception("客户必填", 410);

        try {
            return $this->easyWeChat->external_contact->list($userId);
        } catch (Exception $e) {
            Log::channel("log")->error("external_contact list exception: " . $e->getMessage());
            return false;
        }
    }

    /**
     * 外部联系人详情
     * @param null $externalUserId
     * @return void|null
     */
    public function getExternalUserDetail($externalUserId = null)
    {
        if (empty($externalUserId))
            return null;

        try {
            $res = $this->easyWeChat->external_contact->get($externalUserId);

            if ($res['errcode'] == 0) {
                return array_merge($res['external_contact'] ?? [], $res['follow_user'][0] ?? []);
            }

            return null;
        } catch (Exception $e) {
            return null;
        }
    }

    /**
     * 批量获取客户详情
     * @param https://developer.work.weixin.qq.com/document/path/93010
     * @return void|null
     */
    public function batchGetByUser(array $userId, string $cursor="", int $limit=100)
    {
        try {
            $res = $this->easyWeChat->external_contact->batchGetByUser($userId, $cursor, $limit);
            if($res['errcode'] == 0)
                return $res;
            else
                return $res['errmsg'];
        } catch (Exception $e) {
            return null;
        }
    }

}
